// pages/detail-search/detail-search.js
import { getSearchHot, getSearchSuggest, getSearchResult } from "../../services/search"
import stringToNodes from "../../utils/string2nodes"
import debounce from "../../utils/debounce"

const debounceGetSearchSuggest = debounce(getSearchSuggest, 100)

Page({
  data: {
    hotSerchInfos: [],
    suggestSongs: [],
    resultSongs: [],
    suggestSongsNodes: [],
    searchValue: "",
  },
  onLoad() {
    this.getPageData()
  },

  // api接口函数
  async getPageData() {
    const res = await getSearchHot()
    // console.log(res);
    this.setData({ hotSerchInfos: res.result.hots})
  },

  // ----------页面事件函数
  handleSearchChange(event) {
    // 1.获取输入的关键字
    const searchValue = event.detail
    // 2.保存关键字
    this.setData({searchValue})
    // 3.判断关键字为null的处理逻辑
    if (!searchValue.length) {
      this.setData({ suggestSongs: [], resultSongs: []})
      debounceGetSearchSuggest.cancel()
      return
    }
    // 4.根据关键字进行搜索
    debounceGetSearchSuggest(searchValue).then(res => {
      // 获取关键词字歌曲
      const suggestSongs = res.result.allMatch
      this.setData({suggestSongs})
      if (!suggestSongs) {
        return
      }
      // 转换成node节点
      const suggestKeywords = suggestSongs.map(item => item.keyword)
      const suggestSongsNodes = []
      for (const keyword of suggestKeywords) {
        const nodes = stringToNodes(keyword, searchValue)
        suggestSongsNodes.push(nodes)
      } 
      this.setData({suggestSongsNodes})
    })
  },

  // 搜索结果
  handleSearchAction() {
    const searchValue = this.data.searchValue
    getSearchResult(searchValue).then(res => {
      this.setData({resultSongs: res.result.songs})
    })
  },

  // 点击获取最佳匹配的歌曲
  handleKeywordItemClick(event) {
    console.log(event);
    // 获取关键字
    const keyword = event.currentTarget.dataset.keyword
    // 将关键设置到searchValue中
    this.setData({searchValue:keyword})
    // 发送网络请求
    this.handleSearchAction()
  }
})